package thread;

import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.BlockingDeque;
import java.util.concurrent.BlockingQueue;

/**
 * Description:
 * Date: 2024-03-10
 */
class MyThreadPool { // 模拟实现一个线程池
    private BlockingQueue<Runnable> queue =
            new ArrayBlockingQueue<>(3000); //创建 阻塞队列
    public void submit(Runnable runnable)
            throws InterruptedException {
        queue.put(runnable);
    }
    public MyThreadPool(int n) {
        //创建出N个线程，负责执行上述队列中的任务
        for (int i = 0; i < n; i++) {
            Thread t = new Thread(()->{
                try {
                    Runnable runnable = queue.take();
                    runnable.run();
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }
            });
            t.start();
        }
    }
}
public class Demo10 {
    public static void main(String[] args) throws InterruptedException {
        MyThreadPool myThreadPool = new
                MyThreadPool(4);
        for (int i = 0; i < 4; i++) {
            int id = i; //此处说明一下 我们匿名内部类 在类外获取变量时必须是final 的或者
            //事实上是final 的 此处 id 相当于每次 for循环都会重置一下id  因此id 可以看做是final的
            myThreadPool.submit(new Runnable() {   //匿名内部类
                @Override
                public void run() {
                    System.out.println("执行的任务" +id);
                }
            });
        }
    }
}
